const fs = require("fs");
const path = require("path");
const iconv = require("iconv-lite");
const { loadConfig } = require("./utils/config");
const { generateASSContent } = require("./utils/assGenerator");
const { generateASSStyles } = require("./utils/assStyles");
const { parseEntry } = require("./utils/datParser");
const { srtTimeToSeconds } = require("./utils/common");

// 读取配置文件
const config = loadConfig();

/**
 * 将.dat文件转换为.ass文件
 * @param {string} inputPath - 输入.dat文件路径
 * @param {string} outputPath - 输出.ass文件路径
 * @param {number} audioDuration - 音频时长（秒），可选参数
 */
function convertDatToAss(inputPath, outputPath, audioDuration = null) {
  try {
    // 确保输出目录存在
    const outputDirPath = path.dirname(outputPath);
    if (!fs.existsSync(outputDirPath)) {
      fs.mkdirSync(outputDirPath, { recursive: true });
    }

    // 使用GBK编码读取.dat文件
    const buffer = fs.readFileSync(inputPath);
    const data = iconv.decode(buffer, "gbk");

    // 分割为各个条目
    const entries = data.split("*^").filter(entry => entry.trim() !== "");

    // 生成ASS文件头部
    const textStyles = config.projectSettings?.textStyles || {};
    let assContent = `[Script Info]
Title: Default Aegisub file
ScriptType: v4.00+
WrapStyle: 0
ScaledBorderAndShadow: yes
YCbCr Matrix: TV.601
PlayResX: ${config.projectSettings.videoWidth}
PlayResY: ${config.projectSettings.videoHeight}

[V4+ Styles]
${generateASSStyles(textStyles)}

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
`;

    // 添加字幕内容，传递音频时长参数
    assContent += generateASSContent(entries, audioDuration);

    // 使用UTF-8编码写入ASS文件，并确保BOM以正确显示中文
    fs.writeFileSync(outputPath, "\ufeff" + assContent, "utf8");
    console.log(`Successfully converted ${inputPath} to ${outputPath}`);
  } catch (error) {
    console.error("！！！Error converting file:", error.message);
  }
}

/**
 * 计算DAT文件中所有条目的总时长
 * @param {string} inputPath - 输入.dat文件路径
 * @returns {number} 总时长（秒）
 */
function calculateDatDuration(inputPath) {
  try {
    console.log(`  Calculating duration for DAT file: ${inputPath}`);

    // 检查文件是否存在
    if (!fs.existsSync(inputPath)) {
      console.error(`！！！  DAT file does not exist: ${inputPath}`);
      return 0;
    }

    // 使用GBK编码读取.dat文件
    const buffer = fs.readFileSync(inputPath);
    const data = iconv.decode(buffer, "gbk");

    console.log(`  DAT file content (first 50 chars): ${data.substring(0, 50)}`);

    // 分割为各个条目
    const entries = data.split("*^").filter(entry => entry.trim() !== "");

    console.log(`  Found ${entries.length} entries in DAT file`);

    let totalDuration = 0;

    // 解析所有条目并计算总时长
    entries.forEach((entry, _index) => {
      if (entry.trim() === "") return;
      // console.log(`Parsing entry ${index}: ${entry.substring(0, 50)}...`);
      const parsedEntry = parseEntry("*^" + entry);
      // console.log(`Parsed entry ${index}:`, parsedEntry);

      if (parsedEntry) {
        // 将SRT时间格式转换为秒
        const endTime = srtTimeToSeconds(parsedEntry.endTime);

        // console.log(`Entry ${index} start: ${startTime}, end: ${endTime}`);

        // 更新总时长为最后一个条目的结束时间
        if (endTime > totalDuration) {
          totalDuration = endTime;
        }
      }
    });

    console.log(`  Total DAT duration calculated: ${totalDuration}`);
    return totalDuration;
  } catch (error) {
    console.error("！！！  Error calculating DAT duration:", error.message);
    console.error(error.stack);
    return 0;
  }
}

module.exports = {
  convertDatToAss,
  calculateDatDuration,
};
